package com.xlf.common.rabbitMQ.config;

import com.rabbitmq.client.ConnectionFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@Slf4j
public class MqConfig {


    @Bean
    RabbitTemplate rabbitTemplate(CachingConnectionFactory cachingConnectionFactory) {

        RabbitTemplate rabbitTemplate = new RabbitTemplate(cachingConnectionFactory);
        //手动应答返回的标志
        rabbitTemplate.setConfirmCallback((data, ack, cause) -> {
            String msgId = data.getId();
            if (ack) {
                log.info(msgId + ":消息发送成功");
            } else {
                log.error(msgId + ":消息发送失败");
            }
        });
        return rabbitTemplate;
    }

    /**
     * 这个类封装了对 RabbitMQ 管理端的操作
     * @return
     */
    @Bean
    public RabbitAdmin rabbitAdmin(RabbitTemplate rabbitTemplate) {
        RabbitAdmin rabbitAdmin = new RabbitAdmin(rabbitTemplate);
        rabbitAdmin.setAutoStartup(true);
        rabbitAdmin.setRedeclareManualDeclarations(true);
        return rabbitAdmin;
    }

}
